//获取应用实例
const app = getApp();
var utilMd5 = require('../util/md5.js');
Page({
  data: {
    bannerList: [{}],
    tempBannerList: [{}],
    motto: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    navData: [],
    page: 1,
    currentTab: 0,
    navScrollLeft: 0,
    //准备数据 
    menu: {},
    moduleList2: [],
    goodsList: [],
    pddshopList: [],
    shopList: [],
    navList: [],
    moduleList: [{

    }]
  },

  onReady() {},
  onShow() {
    var that = this
    wx.getStorage({
      key: 'token',
      success: function (res) {
        console.log(res)
        if (res.data != '') {
          app.globalData.token = res.data
          that.getUserMsg();
        }
        console.log("token=" + app.globalData.token)
      },
    })
  },
  checkUpdateVersion: function () {
    var that = this
    //创建 UpdateManager 实例
    const updateManager = wx.getUpdateManager();

    updateManager.onCheckForUpdate(function (res) {
      if (res.hasUpdate == true) {
        updateManager.onUpdateReady(function (res) {
          wx.showModal({
            title: '更新提示!!!',
            content: '新版本已经准备好，是否重启应用？',
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
              }
            }
          })
        })
        updateManager.onUpdateFailed(function () {
          // 新的版本下载失败
          wx.showModal({
            title: '已经有新版本了哟~',
            content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
          })
        })
      }
    })
    updateManager.applyUpdate();
  },
  onLoad: function () {
    var that = this;
    this.checkUpdateVersion()
    that.getBannerList();
    that.getAppSet();
    app.globalData.uid = wx.getStorageSync('uid'); //获取本地缓存中的token
    // this.getTopCatList();

    console.log(app.globalData.sharedgoodId)
    if (app.globalData.sharedgoodId != '') {
      wx.navigateTo({
        url: '/pages/shop/pdd-item?id=' + app.globalData.sharedgoodId,
      })
    }
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          pixelRatio: res.pixelRatio,
          windowHeight: res.windowHeight,
          windowWidth: res.windowWidth
        })
      },
    })
  },

  onShareAppMessage: function () {
    return {
      title: '汇客熊小程序',
      // desc: '欢迎来到淘品优仓小程序',
      path: '/pages/live/splash' // 路径，传递参数到指定页面。
    }
  },

  //获取商品列表
  getGoodsList() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    //获取当前时间戳  
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var code = app.globalData.pdd_client_secret + 'client_id' + app.globalData.pdd_client_id + 'data_typeJSONopt_id0page' + that.data.page + 'page_size20sort_type0timestamp' + timestamp + 'typepdd.ddk.goods.searchwith_coupontrue' + app.globalData.pdd_client_secret;
    console.log(code)
    var MD5code = utilMd5.md5(code); //code需要加密的数据
    wx.request({
      url: app.globalData.apiPdd + '',
      data: {
        page: that.data.page,
        page_size: 20,
        sort_type: 0,
        data_type: 'JSON',
        opt_id: 0,
        client_id: '' + app.globalData.pdd_client_id,
        timestamp: '' + timestamp,
        with_coupon: true,
        type: 'pdd.ddk.goods.search',
        sign: '' + MD5code.toUpperCase()
      },
      header: {
        'Content-type': 'application/x-www-form-urlencoded',
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if (that.data.page > 8) {
          wx.showToast({
            title: '暂无更多数据啦',
            icon: 'none'
          })
        } else {
          that.setData({
            shopList: that.data.shopList.concat(res.data.goods_search_response.goods_list)
          })
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  toTbkdetail: function (e) {
    if (app.globalData.token != '') {
      wx.navigateTo({
        url: '/pages/shop/pdd-item?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.navigateTo({
        url: '/pages/mine/login',
      })
    }

  },
  linqu: function (e) {

    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Pdd&a=judgeUser',
      data: {
        token: app.globalData.token,

      },
      header: {
        'Content-type': 'application/x-www-form-urlencoded',
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {

        console.log('ppp');
        wx.hideLoading();

        if (res.data.code == 0) {
          wx.navigateTo({
            url: '../wmm/pdd_new_index',
          })
        } else {
          setTimeout(function () {
            //要延时执行的代码
            that.getLink();
          }, 500) //延迟时间 这里是1秒

          wx.showToast({
            title: "请先拼多多授权",
            icon: 'none'
          })

        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },
  getLink: function (e) {

    // wx.showLoading({
    //   title: '加载中',
    //   mask: false
    // })
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Pdd&a=getUrl',
      data: {
        token: app.globalData.token,

      },
      header: {
        'Content-type': 'application/x-www-form-urlencoded',
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {

        console.log('ppp');
        // wx.hideLoading();

        if (res.data.code == 0) {
          wx.navigateToMiniProgram({
            appId: res.data.data.url_list[0].we_app_info.app_id,
            path: res.data.data.url_list[0].we_app_info.page_path,
            success(res) {
              console.log(res)
            }
          })
        } else {

          wx.showToast({
            title: '' + res.data.msg,
            icon: 'none'
          })

        }
      },
      fail: function () {
        // wx.hideLoading();
      }
    });
  },
  pddtype: function (e) {
    console.log(e.currentTarget.dataset.index)
    if (e.currentTarget.dataset.index == 2) {
      if (app.globalData.token != "") {
        this.linqu()

      } else {

        wx.navigateTo({
          url: '/pages/mine/login',
        })
      }

    } else {
      wx.navigateTo({
        url: 'pdd-baokuanlist?index=' + e.currentTarget.dataset.index,
      })
    }

  },
  //获取用户信息
  getUserMsg() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    console.log(app.globalData.token)
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=User&a=getUserMsg',
      data: {
        token: app.globalData.token
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.code == 0) {
          that.setData({
            user_msg: res.data.data.user_msg,
            user_detail: res.data.data.user_detail,
            avatar: res.data.data.user_detail.avatar
          })
          app.globalData.phone = res.data.data.user_msg.phone
          app.globalData.nickname = res.data.data.user_detail.nickname,
            app.globalData.weixinid = res.data.data.user_detail.weixin,
            app.globalData.avatar = res.data.data.user_detail.avatar,
            app.globalData.auth_code = res.data.data.user_msg.auth_code,
            app.globalData.group_id = res.data.data.user_msg.group_id,
            app.globalData.uid = res.data.data.user_msg.uid
            app.globalData.truename = res.data.data.user_detail.truename

          app.globalData.balance_pdd = res.data.data.user_msg.balance_pdd

          app.globalData.alipay_account = res.data.data.user_msg.alipay_account

          console.log(app.globalData.phone)
        } else {
          // if (res.data.code == 105) {
          //   wx.removeStorage({
          //     key: 'token',
          //     success: function(res) {
          //       console.log(res)
          //     },
          //   })
          //   app.globalData.token = '';
          //   wx.reLaunch({
          //     url: '/pages/mine/login',
          //   })
          // }
          // wx.showToast({
          //   title: '' + res.data.msg,
          //   icon:'none'
          // })
        }

      },
      fail: function () {

      },
      complete: function () {

      }
    });
  },

  //获取设置信息
  getAppSet() {
    var that = this;
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    wx.request({
      url: app.globalData.api + '/app.php?c=Index&a=getAppSet',
      data: {},
      header: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        app.globalData.pdd_client_id = res.data.data.pdd_client_id
        app.globalData.pdd_client_secret = res.data.data.pdd_client_secret
        that.getGoodsList();
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },


  tomsg: function () {
    wx.navigateTo({
      url: '/pages/mine/message',
    })
  },
  //获取Banner/广告图列表
  getBannerList() {
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Pdd&a=getThemeList',
      data: {},
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        that.setData({
          bannerList: res.data.data.theme_list
        })
        that.getList();
        console.log(that.data.bannerList)
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  //获取首页
  getList() {
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=Diy&a=wxmini',
      data: {},
      header: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.data.moduleList.length > 0) {
          for (var i = 0; i < res.data.data.moduleList.length; i++) {
            res.data.data.moduleList[i].icon = app.globalData.imgUrl + "" + res.data.data.moduleList[i].icon;
          }
          that.setData({
            moduleList: res.data.data.moduleList
          })
          console.log(that.data.moduleList.length);
        } else {
          that.setData({
            moduleList: ""
          })
        }
      },
      fail: function () {
        wx.hideLoading();
      }
    });
  },

  themeDetail: function (e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/mine/theme-list?id=' + e.currentTarget.dataset.id + '&name=' + e.currentTarget.dataset.name,
    })
  },

  goodMenuDetail: function (e) {
    console.log(e)
    console.log(app.globalData.token)
    if (app.globalData.token != '') {
      console.log(e);
      this.setData({
        navList: [],
        searchName: e.currentTarget.dataset.name,
        page: 1
      })
    } else {
      wx.reLaunch({
        url: '/pages/mine/login',
      })
    }
  },

  goodDetail: function (e) {
    console.log(app.globalData.token)
    if (app.globalData.token != '') {
      console.log(e);
      wx.navigateTo({
        url: '/pages/shop/item?id=' + e.currentTarget.dataset.id,
      })
    } else {
      wx.reLaunch({
        url: '/pages/mine/login',
      })
    }
  },
  mainTap: function (e) {
    console.log(e)
    wx.navigateTo({
      url: '/pages/shop/webview?index=' + e.currentTarget.dataset.index,
    })
  },
  jdlbTap: function () {
    wx.navigateTo({
      url: '/pages/shop/hdlb',
    })
  },

  //首页进入商品列表
  toGoodList: function (e) {
    console.log(e)
    if (e.currentTarget.dataset.index == 1) {
      wx.navigateTo({
        url: '/pages/shop/zero-good-list?index=' + e.currentTarget.dataset.index,
      })
    } else {
      wx.navigateTo({
        url: '/pages/shop/good-list?index=' + e.currentTarget.dataset.index,
      })
    }
  },
  toDetail: function (e) {
    console.log(e)
    if (e.currentTarget.dataset.index == 0) {
      wx.switchTab({
        url: '/pages/live/jingdong',
      })
    } else if (e.currentTarget.dataset.index == 1) {
      wx.navigateTo({
        url: '/pages/live/pinduoduo',
      })
    } else if (e.currentTarget.dataset.index == 7) {
      wx.navigateTo({
        url: '/pages/live/jiayou',
      })
    } else {
      wx.showToast({
        title: '功能正在开发中',
        icon: 'none'
      })
    }
  },
  toSearch: function () {
    wx.navigateTo({
      url: '/pages/mine/search-history',
    })
  },

  switchNav(event) {
    var cur = event.currentTarget.dataset.current;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })

    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
    console.log(this.data.currentTab)
    this.getChildList(this.data.currentTab);
  },
  switchTab(event) {
    var cur = event.detail.current;
    var singleNavWidth = this.data.windowWidth / 5;
    this.setData({
      currentTab: cur,
      navScrollLeft: (cur - 2) * singleNavWidth
    });
  },
  switchTabGoodType(event) {
    var cur = event.detail.current;
    var singleNavWidth = this.data.windowWidth / 5;
    this.setData({
      currents: cur,
      navScrollLeft: (cur - 2) * singleNavWidth
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    wx.showNavigationBarLoading(); //在标题栏中显示加载图标
    setTimeout(function () {
      wx.stopPullDownRefresh(); //停止加载
      wx.hideNavigationBarLoading(); //隐藏加载icon
    }, 2000)
    this.setData({
      page: 1,
      shopList: []
    })
    // that.getGoodsList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    that.setData({
      page: that.data.page + 1
    })
    that.getGoodsList();
  },

});